<template>
  <div class="charge-off-record">
    <div style="margin-bottom:10px;display:flex;align-items:center;">
      <Title title="核销记录" />
      <PlainCreateBtn
        v-if="!hideAllOperation && isNotAddAccount && records.unWriteOffAmount"
        size="small"
        @click="addDrawerOpen">添加核销</PlainCreateBtn>
    </div>
    <div class="middle-box">
      <dataDisplay
        v-if="records"
        :data-list="[
          {data: records.totalTaxAmount / 100, label: '总含税金额', icon: incomeAmount },
          {data: records.completeWriteOffAmount / 100, label: '已核销金额', icon: chargeOffStatus },
          {data: records.unWriteOffAmount / 100, label: '待核销金额', icon: moneyIcon },
          {data: setVerificationState(records.writeOffStatus), label: '核销状态', placeholder: setVerificationState(records.writeOffStatus), icon: statusIcon }
        ]"
        type="row"
        style="width:100%;"
      />
    </div>
    <div class="record-table">
      <template v-if="records && records.list && records.list.length">
        <el-table
          ref="resourceTable"
          :data="handleData(records.list)"
          class="fb-table"
          row-key="id"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
        >
          <el-table-column label="核销日期" width="120px">
            <template slot-scope="scope">
              <span v-if="scope.row.writeOffTime">{{ scope.row.writeOffTime | parseTime('{y}/{m}/{d}') }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="核销金额(元)" align="right" width="140px">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.incomeAmount" :price="scope.row.incomeAmount" />
              <span v-if="scope.row.isLoseEfficacy === 1" style="color: #E54C4C">(已重置)</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isClientInfo" label="付款人" width="120">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.paymentUser" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.paymentUser }}</div>
                <div class="ellipsis">{{ scope.row.paymentUser }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="付款方式" min-width="120px">
            <template slot-scope="scope">
              <ToolTip :content="getPayWay(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column v-if="isClientInfo" label="付款账号" min-width="100px">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.paymentAccount" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.paymentAccount }}</div>
                <div class="ellipsis">{{ scope.row.paymentAccount }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="交易单号" min-width="120px">
            <template slot-scope="scope">
              <div v-if="scope.row.transactionNumber" class="light-word" @click="toFinanceDetail(scope.row)">
                <ToolTip :content="scope.row.transactionNumber"/>
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="流水单号" min-width="120px">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.flowNumber" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.flowNumber }}</div>
                <div class="ellipsis">{{ scope.row.flowNumber }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="到账日期" width="120px">
            <template slot-scope="scope">
              {{ scope.row.arrivalTime | parseTime('{y}/{m}/{d}') }}
            </template>
          </el-table-column>
          <el-table-column label="流水创建人员" width="110px">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.createUserId" :user-id="scope.row.createUserId" :label="scope.row.createName" />
              <div v-else>{{ scope.row.createName || '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="核销人员">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.writeOffUserId" :user-id="scope.row.writeOffUserId" :label="scope.row.writeOffUser" />
              <div v-else>{{ scope.row.writeOffUser || '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="类型">
            <template slot-scope="scope">
              {{ scope.row.flowType | flowType }}
            </template>
          </el-table-column>
          <el-table-column label="封账状态">
            <template slot-scope="scope">
              <StatusText :color="['#406eff','#31cc9c', '#fd854d'][scope.row.sealBillType]" :text="scope.row.sealBillType | setSealBillType" />
            </template>
          </el-table-column>
          <el-table-column v-if="!hideAllOperation" align="left" label="撤销核销" width="140" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="!disabled && scope.row.sealBillType === 0"
                :disabled="scope.row.sealBillType !== 0 || disabled"
                type="text"
                size="small"
                @click="toCancel(scope)"
              >撤销核销</el-button>
              <el-button
                v-if="scope.row.sealBillType === 1 && !disabled && hasRouteAuth('crm:orderList:resetChargeOff')"
                type="text"
                size="small"
                @click="toResetChargeOff(scope)">
                重置核销
              </el-button>
              <span v-if="!((scope.row.sealBillType === 0 || scope.row.sealBillType === 1 && hasRouteAuth('crm:orderList:resetChargeOff'))&& !disabled)">--</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="(records.list.length > 10)" style="margin-top:12px;display:flex;">
          <span style="flex:1"/>
          <el-pagination
            :page-sizes="[10, 50, 100, 250, 500]"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="records.list.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </template>
      <div v-else class="empty-container">
        <div class="empty-box">
          <img src="../../../assets/empty-invoice.png" alt="">
          <div class="empty-text">暂无数据</div>
        </div>
      </div>
    </div>
    <WriteOfFinancialFlowDrawer
      ref="writeOfFinancialFlowRef"
      :order-id="orderId"
      :client-id="clientId"
      :order-type="orderType"
      :is-show-month="true"
      :write-off-amount="records.unWriteOffAmount"
      @enterSuccess="enterSuccess" />
  </div>
</template>
<script>
import Title from '@/components/Title';
import WriteOfFinancialFlowDrawer from '@/components/Common/writeOfFinancialFlow';
import incomeAmount from '@/assets/chargeOffDetail/incomeAmount.png';
import chargeOffStatus from '@/assets/chargeOffDetail/chargeoff_status.png';
import moneyIcon from '@/assets/dataDisplay/rmb.png';
import statusIcon from '@/assets/chargeOffDetail/status_icon.png';
import { setVerificationState, setSealBillType, clientStatusFilter } from '@/filters/status';
import { parseTime } from '@/utils/index';
import { moneyFilter } from '@/filters/number';
import { hasRouteAuth } from '@/utils/permission';
import { cancelWriteOff, resetWriteOff } from '@/api/finance';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import '@/styles/extend.scss';
export default {
  name: 'ChargeOffRecord',
  components: {
    Title,
    WriteOfFinancialFlowDrawer,
    dataDisplay
  },
  filters: {
    setVerificationState,
    parseTime,
    moneyFilter,
    setSealBillType,
    flowType(val) {
      // 流水类型。0:普通 1:对抵
      let text = '--';
      switch (val) {
        case 0:
          text = '普通';
          break;
        case 1:
          text = '对抵';
          break;
      }
      return text;
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    isNotAddAccount: {
      type: Boolean,
      default: true
    },
    records: {
      type: Object,
      default: () => {
        return null;
      }
    },
    orderId: {
      type: Number,
      default: null
    },
    clientName: {
      type: String,
      default: ''
    },
    clientId: {
      type: Number,
      default: null
    },
    titleSize: {
      type: String,
      default: '20px'
    },
    orderType: {
      type: Number,
      default: null
    },
    hideAllOperation: {
      type: Boolean,
      default: false
    },
    orderStatus: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      moneyIcon,
      statusIcon,
      chargeOffStatus,
      incomeAmount,
      listLoading: false,
      currentPage: 1,
      pageSize: 10,
      antiShakeTime: 0 // 防抖时间
    };
  },
  computed: {
    isClientInfo() {
      return hasRouteAuth('crm:orderList:clientInfo');
    }
  },
  methods: {
    hasRouteAuth,
    setVerificationState,
    clientStatusFilter,
    toResetChargeOff(scope) {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      this.$confirm('请确认是否重置核销，重置后原核销记录将会失效，可重新核销订单', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.listLoading = true;
        // if (this.records) {
        //   ids = this.records.list.map(item => {
        //     return item.id;
        //   }).join(',');
        // } else {
        //   ids = [];
        // }
        const param = {
          ids: [scope.row.id]
        };
        resetWriteOff(param).then(res => {
          this.listLoading = false;
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '重置核销成功，原核销记录已失效'
            });
            this.$emit('getDetail');
          }
        }).catch((_) => {
          this.listLoading = false;
        });
      }).catch(() => {
        this.listLoading = false;
        return;
      });
    },
    toCancel(scope) {
      this.listLoading = true;
      this.$confirm('确定撤销核销？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.listLoading = false;
        const params = {};
        if (this.orderType || this.orderType === 0) {
          params.type = 2;
        }
        cancelWriteOff(scope.row.id, params).then(res => {
          this.listLoading = false;
          this.$emit('getDetail');
        }, result => {
          this.listLoading = false;
        });
      }).catch(() => {
        this.listLoading = false;
        return;
      });
    },
    addDrawerOpen() {
      this.$refs['writeOfFinancialFlowRef'].initData(this.records.unWriteOffAmount, { clientName: this.clientName });
    },
    enterSuccess() {
      this.$emit('getDetail');
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    },
    getPayWay(row) {
      const clientType = this.clientStatusFilter(row.clientType);
      return row.paymentMethod ? clientType + ' / ' + row.paymentMethod : clientType;
    },
    toFinanceDetail(row) {
      const url = this.$router.resolve({
        name: 'chargeOffDetail',
        params: { chargeOffId: row.financeTxnId }
      });
      window.open(url.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.charge-off-record {
  padding: 0 24px;
  margin-top: 22px;
  margin-bottom: 33px;
  .middle-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    // text-align: right;
    margin-bottom: 16px;
    align-items: center;
  }
  .el-table--scrollable-y .el-table__body-wrapper {
    width: 99%;
  }
}
.empty-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #EBEEFD;
  padding: 12px 0 18px 0;
  .empty-box {
    display: flex;
    align-items: center;
  }
  img {
    width: 12px;
    margin-right: 4px;
  }
  .empty-text {
    color: #999;
    font-size: 14px;
  }
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
</style>
